package com.ttc.mBackup.BackupAgent;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.dropbox.client.DropboxAPI;
import com.dropbox.client.DropboxAPI.Config;
import com.dropbox.client.DropboxAPI.Entry;
import com.ttc.mBackup.R;

public class LoginDropbox extends Activity{

	 private static final String TAG = "DropboxSample";

	    // Replace this with your consumer key and secret assigned by Dropbox.
	    // Note that this is a really insecure way to do this, and you shouldn't
	    // ship code which contains your key & secret in such an obvious way.
	    // Obfuscation is good.
	    final static public String CONSUMER_KEY = "mbbzpdsyjpaemod";
	    final static public String CONSUMER_SECRET = "z9vzafyd2u6ryph";
	    /*ProgressDialog*/
		private ProgressDialog _progress;
	    private DropboxAPI api = new DropboxAPI();

	    final static public String ACCOUNT_PREFS_NAME = "prefs";
	    final static public String ACCESS_KEY_NAME = "ACCESS_KEY";
	    final static public String ACCESS_SECRET_NAME = "ACCESS_SECRET";
	    
		public static final String ACCOUNT_DROPBOX="account";
		public static final String PASSWORD_DROPBOX="password";
		public static final String LOG_DROPBOX="log";
		public static final String SHOW_DROPBOX="show";
		
		
	    private boolean mLoggedIn;
	    private EditText mLoginEmail;
	    private EditText mLoginPassword;
	    private Button mSubmit;
	    private Config mConfig;
	    private CheckBox check_view;
	    /** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        setContentView(R.layout.logindropbox);
	        
	        mLoginEmail = (EditText)findViewById(R.id.login_email);
	        mLoginPassword = (EditText)findViewById(R.id.login_password);
	        mSubmit = (Button)findViewById(R.id.login_submit);
	       // mText = (TextView)findViewById(R.id.text);
	        check_view= (CheckBox) findViewById(R.id.show_check);
	        mSubmit.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	if (!mLoggedIn) {
	            		// Try to log in
	            		 showDialog(0);
	            		getAccountInfo(mLoginEmail.getText().toString(), 
	            				mLoginPassword.getText().toString());	
	            	}
	            }
	        });
	        check_view.setOnCheckedChangeListener(new OnCheckedChangeListener()
	        {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					if(isChecked){
					mLoginPassword.setInputType(1);
					}
					else
					{mLoginPassword.setInputType(129);}
					
				}});

	        
	    }

	    public ArrayList<Entry> listDirectory(String path, DropboxAPI api) {
	    	
	    	DropboxAPI.Entry entry = api.metadata("dropbox", path, 0, null, true);
	    	if (!entry.is_dir) return null;
	    	return entry.contents;
	    	}
	    
	    
	    /**
	     * This lets us use the Dropbox API from the LoginAsyncTask
	     */
	    public DropboxAPI getAPI() {
	    	return api;
	    }

	    /**
	     * Convenience function to change UI state based on being logged in
	     */
	    public void setLoggedIn(boolean loggedIn) {
	    	mLoggedIn = loggedIn;
	    	if (loggedIn) {
	    		
	    		saveinfo();
	    		
	    	}   
	    	_progress.dismiss();
	    }

	    public void showToast(String msg) {
	        Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
	        error.show();
	    }
	    
	    public void getAccountInfo(String email,String password) {
	    	if (api.isAuthenticated()) {
	    		// If we're already authenticated, we don't need to get the login info
		        LoginAsyncTask login = new LoginAsyncTask(this, null, null, getConfig());
		        login.execute();    		
	    	} else {
	    	
		 
		        if (email.length() < 5 || email.indexOf("@") < 0 || email.indexOf(".") < 0) {
		            showToast("Error, invalid e-mail");
		            _progress.dismiss();
		            return;
		        }
		
		      
		        if (password.length() < 6) {
		            showToast("Error, password too short");
		            _progress.dismiss();
		            return;
		        }

		        // It's good to do Dropbox API (and any web API) calls in a separate thread,
		        // so we don't get a force-close due to the UI thread stalling.
		        LoginAsyncTask login = new LoginAsyncTask(this, email, password, getConfig());
		        login.execute();
	    	}
	    }

	  
	    
	 
	    
	    protected Config getConfig() {
	    	if (mConfig == null) {
		    	mConfig = api.getConfig(null, false);
		    	// TODO On a production app which you distribute, your consumer
		    	// key and secret should be obfuscated somehow.
		    	mConfig.consumerKey=CONSUMER_KEY;
		    	mConfig.consumerSecret=CONSUMER_SECRET;
		    	mConfig.server="api.dropbox.com";
		    	mConfig.contentServer="api-content.dropbox.com";
		    	mConfig.port=80;
	    	}
	    	return mConfig;
	    }
	    
	    public void setConfig(Config conf) {
	    	mConfig = conf;
	    }
	    
	   
	    /**
	     * Shows keeping the access keys returned from Trusted Authenticator in a local
	     * store, rather than storing user name & password, and re-authenticating each
	     * time (which is not to be done, ever).
	     */
	    public void storeKeys(String key, String secret) {
	        // Save the access key for later
	        SharedPreferences prefs =getSharedPreferences(ACCOUNT_PREFS_NAME, MODE_WORLD_WRITEABLE);
	        Editor edit = prefs.edit();
	        edit.putString(ACCESS_KEY_NAME, key);
	        edit.putString(ACCESS_SECRET_NAME, secret);
	        edit.commit();
	    }
	    
	/*    public void clearKeys() {
	        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
	        		MODE_WORLD_WRITEABLE);
	        Editor edit = prefs.edit();
	        edit.clear();
	        edit.commit();
	    }*/   
		private void saveinfo()
		{
			
			SharedPreferences pref = getSharedPreferences(ACCOUNT_PREFS_NAME, 
					MODE_WORLD_WRITEABLE);
			SharedPreferences.Editor editor = pref.edit();
			
			//--- put info of user
			editor.putBoolean(SHOW_DROPBOX, check_view.isChecked());
			editor.putString(ACCOUNT_DROPBOX, mLoginEmail.getText().toString());
			editor.putString(PASSWORD_DROPBOX, mLoginPassword.getText().toString());
			
			if(!pref.getBoolean(LOG_DROPBOX, false))
				{
				Intent i = new Intent();
	    		i.putExtra("KEY",mLoggedIn );
	    		setResult(RESULT_OK,i);
				editor.putBoolean(LOG_DROPBOX, mLoggedIn);
				/*Create Folder*/
				api.createFolder("dropbox", "BackupSystems");
				api.createFolder("dropbox", "SMSBackup");
				api.createFolder("dropbox", "ImageBackup");
				api.createFolder("dropbox", "ContactBackup");
			api.deauthenticate();
	    	///	clearKeys();
	    		finish();
				}
			
		//--- Save info
			editor.commit();
			
		}
		
		@Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			_progress =  ProgressDialog.show(this, "",
					"Please wait for few seconds...", true);
			return _progress;
			
		}
   
    }


